import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { SelectC, ProductListC, TradingCompanyC, SecuritiesCodeC, InputNumberC, InputC, SingleDateC, codeType } from '../../../../comps';
import { connect } from 'dva';
import { config1, dict, priceTypeData } from '../config';
import shareOptionStyle from '../shareOptionStyle.less';
import moment from 'moment';
import { isZiGuanEvir } from '../../../../utils/commonFunc';
@Form.create()
@connect(({ shareOptionManageM, bookM, globalM }) => ({ shareOptionManageM, bookM, globalM }))
export default class BaseOption extends PureComponent {
  state = {
    Dis1: true, //名义本金和名义数量是否禁用
    Dis2: true, //期权费和期权费率是否禁用
    Dis3: false, //禁用行权方向，行权价格，行权价格率
    counterparty: '', // 记录交易对手
    jydsList: [], // 交易对手list
    exchangeCode: undefined, // 交易场所 由标的证券带出
    isZiGuan: false,
    tradeDateT: '',
    effectiveDateT: '',
    expiryDateT: '',
    settleDateT: '',
    priceIndex: -1,
  };
  componentDidMount() {
    const { bookMain, type } = this.props;
    this.props.onRef(this);
    if (bookMain) {
      this.setState({
        counterparty: bookMain.counterparty || '',
      });
      if (bookMain.optionType) {
        this.structureChange(bookMain.optionType);
      }
      if (type == '2' || type == '3') {
        this.setState({ Dis1: false, Dis2: false });
      }
      if (bookMain.effectiveDate) {
        this.props.beginDate(moment(bookMain.effectiveDate));
      }
      if (bookMain.expiryDate) {
        this.props.endDate(moment(bookMain.expiryDate));
      }
      if (bookMain.underlyingType == 'index') {
        this.setState({ priceIndex: 'index' });
      } else if (bookMain.underlyingType == 'gp') {
        this.setState({ priceIndex: 'gp' });
      } else {
        this.setState({ priceIndex: 'ut' });
      }
    }
    let temp = isZiGuanEvir();
    this.setState({ isZiGuan: !!temp });
  }

  // 交易对手改变事件
  counterpartyChange = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    if (e) {
      setFieldsValue({
        'bookMain.counterpartyId': e.value,
      });
      this.setState({
        counterparty: e.title,
      });
    }
  };

  // 标的证券改变
  underlyingChange = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    if (e) {
      setFieldsValue({
        'bookMain.underlyingType': e.underyingType,
      });
      if (e.underyingType == 'index') {
        this.setState({ priceIndex: 'index' });
      } else if (e.underyingType == 'gp') {
        this.setState({ priceIndex: 'gp' });
      } else {
        this.setState({ priceIndex: 'ut' });
      }
      this.setState({
        exchangeCode: e.exchangeCode,
      });
    } else {
      setFieldsValue({
        'bookMain.underlyingType': '',
      });
      this.setState({ priceIndex: -1 });
    }
  };

  // 获取表单数据
  getSettingInfo = () => {
    const {
      form: { getFieldsValue, validateFieldsAndScroll },
      structure,
    } = this.props;
    let formData = getFieldsValue();
    let result = undefined;
    validateFieldsAndScroll((error, values) => {
      if (error) {
        return false;
      } else {
        let bookMain = _.cloneDeep(formData.bookMain);
        // 时间类型的转为字符串
        // 交易日期,起始日期,到期日期，结算日期
        bookMain.tradeDate = bookMain.tradeDate ? bookMain.tradeDate.format('YYYYMMDD') : undefined;
        bookMain.effectiveDate = bookMain.effectiveDate ? bookMain.effectiveDate.format('YYYYMMDD') : undefined;
        bookMain.expiryDate = bookMain.expiryDate ? bookMain.expiryDate.format('YYYYMMDD') : undefined;
        bookMain.settleDate = bookMain.settleDate ? bookMain.settleDate.format('YYYYMMDD') : undefined;
        bookMain.premiumDate = bookMain.premiumDate ? bookMain.premiumDate.format('YYYYMMDD') : undefined;
        bookMain.counterparty = this.state.counterparty;
        bookMain.exchangeCode = this.state.exchangeCode;

        // 名义本金和名义数量二选一必填
        // notional  quantity
        if (!bookMain.notional && !bookMain.quantity) {
          message.error('名义本金和名义数量二选一必填');
          return false;
        }
        // 行权价格率和行权价格中二选一必填一个。二元期权非必填
        // strikeRate strike
        if (structure !== '3') {
          if (!bookMain.strikeRate && !bookMain.strike) {
            message.error('行权价格率和行权价格中二选一必填');
            return false;
          }
        }
        // 有期权费或期权费率时则必填
        // premium premiumRate
        if (!bookMain.premiumDate) {
          if (bookMain.premiumRate || bookMain.premium) {
            message.error('有期权费或期权费率时,期权费支付日期则必填');
            return false;
          }
        }
        result = bookMain;
      }
    });
    return result;
  };
  // 期权结构变化
  structureChange = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue({
      'bookMain.optionType': e,
    });
    // 二元期权子表  禁用行权方向，行权价格，行权价格率
    if (e == '3') {
      this.setState({
        Dis3: true,
      });
      setFieldsValue({
        'bookMain.excerciseDir': undefined,
        'bookMain.strikeRate': undefined,
        'bookMain.strike': undefined,
      });
    } else {
      this.setState({
        Dis3: false,
      });
    }
  };
  // 期初价格改变
  initialPriceChange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
      structure,
    } = this.props;
    // 期初价格改变，则 行权价格率和行权价格要重新填写
    setFieldsValue({
      'bookMain.strikeRate': undefined,
      'bookMain.strike': undefined,
    });
    // ~ 则改变计算出名义数量
    if (e) {
      // 名义本金
      const notional = getFieldValue('bookMain.notional');
      let quantity = undefined;
      if (notional) {
        quantity = Math.round((notional / e) * 100) / 100;
      }
      this.setState(
        {
          Dis1: false,
        },
        () => {
          setFieldsValue({
            'bookMain.quantity': quantity,
          });
        },
      );
    } else {
      this.setState(
        {
          Dis1: true,
        },
        () => {
          setFieldsValue({
            'bookMain.notional': undefined,
            'bookMain.quantity': undefined,
          });
        },
      );
    }
    // 导致障碍组件和二元组件
    this.props.onInitialPriceChange(e);
  };
  // 名义本金变化   名义本金变化导致期权费变化 和名义数量改变
  notionalChange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    if (e) {
      // 计算名义数量
      // 期初价格
      const initialPrice = getFieldValue('bookMain.initialPrice');
      let quantity = undefined;
      if (initialPrice) {
        quantity = Math.round((e / initialPrice) * 100) / 100;
      }
      setFieldsValue({
        'bookMain.quantity': quantity,
      });
      // 名义本金变化，期权费和期权费率重写
      this.setState(
        {
          Dis2: false,
        },
        () => {
          setFieldsValue({
            'bookMain.premium': undefined,
            'bookMain.premiumRate': undefined,
          });
        },
      );
    } else {
      this.setState(
        {
          Dis2: true,
        },
        () => {
          setFieldsValue({
            'bookMain.premium': undefined,
            'bookMain.premiumRate': undefined,
            'bookMain.quantity': undefined,
          });
        },
      );
    }
  };

  // 期权费率变化-导致期权费变化(率时%要有100的乘除)
  premiumRateChange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    // 名义本金
    const notional = getFieldValue('bookMain.notional');
    if (e && notional) {
      setFieldsValue({
        'bookMain.premium': Math.round((e / 100) * notional * 100) / 100,
      });
    } else {
      setFieldsValue({
        'bookMain.premium': undefined,
        'bookMain.premiumRate': undefined,
      });
    }
  };
  // 期权费变化 -导致期权费率变化(率时%要有100的乘除)
  premiumChange = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.props;
    // 名义本金
    const notional = getFieldValue('bookMain.notional');
    if (e && notional) {
      setFieldsValue({
        'bookMain.premiumRate': Math.round((e / notional) * 100 * 100) / 100,
      });
    } else {
      setFieldsValue({
        'bookMain.premium': undefined,
        'bookMain.premiumRate': undefined,
      });
    }
  };
  // 行权价格率变化-导致行权价格变化(率时%要有100的乘除)
  strikeRateChange = (e) => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.props;
    // 期初价格
    const initialPrice = getFieldValue('bookMain.initialPrice');
    if (initialPrice) {
      if (e) {
        let strike = Math.round((e / 100) * initialPrice * 100) / 100; //获取两位小数
        setFieldsValue({
          'bookMain.strike': strike,
        });
      } else {
        setFieldsValue({
          'bookMain.strike': undefined,
        });
      }
    }
  };
  // 行权价格变化-导致行权价格率变化(率时%要有100的乘除)
  strikeChange = (e) => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.props;
    // 期初价格
    const initialPrice = getFieldValue('bookMain.initialPrice');
    if (initialPrice) {
      if (e) {
        let strikeRate = Math.round((e / initialPrice) * 100 * 100) / 100; //获取两位小数
        setFieldsValue({
          'bookMain.strikeRate': strikeRate,
        });
      } else {
        setFieldsValue({
          'bookMain.strikeRate': undefined,
        });
      }
    }
  };
  // 表单重置
  resetForm = () => {
    this.props.form.resetFields();
  };
  render() {
    const {
      form: { getFieldDecorator },
      bookMain,
      structure,
      bookM: { onlyView },
      type,
      globalM: { dataDictionary: dictionary },
    } = this.props;
    const { Dis1, Dis2, Dis3, tradeDateT, effectiveDateT, expiryDateT, settleDateT } = this.state;
    const { info } = config1[0]; // 配置文件中 基础期权的标题配置
    // 是否年化
    const isAnnualizedSelect = [
      { title: '是', value: '1', key: 'isAnnualizedSelect1' },
      { title: '否', value: '2', key: 'isAnnualizedSelect2' },
    ];
    // 判读当前是否为二元期权禁用 是则false 否则为true
    let Required1 = structure && structure == '3' ? false : true;
    // 整个组件是否只读
    const disabledImportant = onlyView;
    // 生成Input
    //
    const generateInput = ({ key, max, initialValue }) => {
      return (
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <InputC
            form={this.props.form}
            dataIndex={'bookMain.' + key}
            title=''
            maxLength={max || 50}
            disabled={info[key].isGrey || disabledImportant}
            initialValue={initialValue == 'reuse' ? undefined : initialValue || bookMain[key]}
            rules={[{ required: info[key].isRequired, message: '此为必填项' }]}
          />
        </div>
      );
    };
    // 生成InputNumber
    const generateInputNumber = ({ key, unit, disabled, onChange, precision }) => {
      return (
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <InputNumberC
            form={this.props.form}
            dataIndex={'bookMain.' + key}
            title=''
            disabled={disabled || info[key].isGrey || disabledImportant}
            unit={unit}
            precision={precision ? precision : undefined}
            initialValue={bookMain[key]}
            rules={[{ required: info[key].isRequired, message: '此为必填项' }]}
            onChange={onChange ? (e) => onChange(e) : undefined}
          />
        </div>
      );
    };
    // 普通的select
    const generateSelect = ({ key, data, isRequired, onChange, disabled }) => {
      let dictArr = [];
      if (dict[key] && dictionary[dict[key]]) {
        dictArr = dictionary[dict[key]].map((item) => {
          return { title: item.value, value: item.code };
        });
      }
      let arr = data || dictArr || [];

      return (
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SelectC
            style={{ width: '100%', height: '100%' }}
            dataIndex={'bookMain.' + key}
            form={this.props.form}
            dataSource={arr}
            placeholder=''
            disabled={info[key].isGrey || disabledImportant || disabled}
            initialValue={bookMain[key]}
            rules={[{ required: isRequired ? true : info[key].isRequired, message: '此为必填项' }]}
            positionBody={true}
          />
        </div>
      );
    };
    // 生成日期
    const generateDatePicker = ({ key }) => {
      let val = undefined;
      if (bookMain[key]) {
        val = moment(bookMain[key]);
      }
      return (
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SingleDateC
            form={this.props.form} // form对象
            dataIndex={'bookMain.' + key}
            title=''
            placeholder=''
            disabled={info[key].isGrey || disabledImportant}
            initialValue={val}
            rules={[{ required: info[key].isRequired, message: '此为必填项' }]}
          />
        </div>
      );
    };

    return (
      <div className={shareOptionStyle.BaseOption}>
        {/* 期权类型 */}
        {generateSelect({ key: 'optionType' })}
        {/* 是否年化 */}
        {generateSelect({ key: 'isAnnualized', data: isAnnualizedSelect })}
        {/* 交易状态 */}
        {generateInput({ key: 'tradeStatus', initialValue: type != '2' ? (bookMain['tradeStatus'] ? bookMain['tradeStatus'] : undefined) : 'reuse' })}
        {/* 交易编号 */}
        {/* {generateInput({key:'tradeId'})} */}
        {/* 合约编号 */}
        {generateInput({ key: 'contractId' })}
        {/* ,marginBottom:info['productId'].space */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          {/* 产品名称 */}
          <ProductListC
            form={this.props.form}
            title=''
            placeholder=''
            dataIndex='bookMain.productId'
            dataType={2}
            disabled={disabledImportant}
            initialValue={bookMain['productId']}
            rules={[{ required: info['productId'].isRequired, message: '此为必填项' }]}
            onRef={(ref) => this.setState({ ProductListC1: ref })}
            tradeModel={['BOOKKEEPING_MODE', 'COMMAND_MODE']} //只有簿记和指令模式产品
            positionBody={true}
          />
        </div>

        {/* 交易对手 */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <TradingCompanyC
            form={this.props.form}
            title=''
            dataIndex={'bookMain.counterpartyId'}
            dataType={2}
            isOtc={'1'}
            disabled={info['counterpartyId'].isGrey || disabledImportant}
            initialValue={bookMain['counterparty']}
            rules={[{ required: info['counterpartyId'].isRequired, message: '此为必填项' }]}
            onChange={(e) => this.counterpartyChange(e)}
          />
        </div>

        {/* 证券编码 */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SecuritiesCodeC
            form={this.props.form}
            title=''
            titleDisplay={false}
            // style={{width:'100%',marginBottom:info['tradingCode'].space}}
            dataIndex='bookMain.tradingCode'
            disabled={disabledImportant}
            onChange={(e) => this.underlyingChange(e)}
            codeType={codeType.cwqq}
            initialValue={bookMain['tradingCode'] ? bookMain['exchangeCode'] + '-' + bookMain['tradingCode'] : undefined}
            rules={[{ required: info['tradingCode'].isRequired, message: '此为必填项' }]}
            positionBody={true}
          />
        </div>

        {/* 交易市场 tradingCode  证券编码exchangeCode 交易市场*/}
        {/* {generateInput({key:'exchangeCode'})} */}
        {/* 标的类型 */}
        {generateSelect({ key: 'underlyingType' })}
        {/* 交易日期 */}
        {/* {generateDatePicker({key:'tradeDate'})} */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SingleDateC
            form={this.props.form} // form对象
            dataIndex={'bookMain.' + 'tradeDate'}
            title=''
            placeholder=''
            disableEnd={
              effectiveDateT ? moment(effectiveDateT).add(1, 'day') : expiryDateT ? moment(expiryDateT).add(1, 'day') : settleDateT ? moment(settleDateT).add(1, 'day') : ''
            }
            disabled={info['tradeDate'].isGrey || disabledImportant}
            initialValue={bookMain['tradeDate'] ? moment(bookMain['tradeDate']) : undefined}
            rules={[{ required: info['tradeDate'].isRequired, message: '此为必填项' }]}
            onChange={(e) => this.setState({ tradeDateT: e ? e : '' })}
          />
        </div>
        {/* 起始日期 */}
        {/* {generateDatePicker({key:'effectiveDate'})} */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SingleDateC
            form={this.props.form} // form对象
            dataIndex={'bookMain.' + 'effectiveDate'}
            title=''
            placeholder=''
            disableBegin={tradeDateT ? moment(tradeDateT).subtract(1, 'day') : ''}
            disableEnd={expiryDateT ? moment(expiryDateT).add(1, 'day') : settleDateT ? moment(settleDateT).add(1, 'day') : ''}
            disabled={info['effectiveDate'].isGrey || disabledImportant}
            initialValue={bookMain['effectiveDate'] ? moment(bookMain['effectiveDate']) : undefined}
            rules={[{ required: info['effectiveDate'].isRequired, message: '此为必填项' }]}
            onChange={(e) => this.setState({ effectiveDateT: e ? e : '' }, () => this.props.beginDate(e))}
          />
        </div>
        {/* 到期日期 */}
        {/* {generateDatePicker({key:'expiryDate'})} */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SingleDateC
            form={this.props.form} // form对象
            dataIndex={'bookMain.' + 'expiryDate'}
            title=''
            placeholder=''
            disableBegin={effectiveDateT ? moment(effectiveDateT).subtract(1, 'day') : tradeDateT ? moment(tradeDateT).subtract(1, 'day') : ''}
            disableEnd={settleDateT ? moment(settleDateT).add(1, 'day') : ''}
            disabled={info['expiryDate'].isGrey || disabledImportant}
            initialValue={bookMain['expiryDate'] ? moment(bookMain['expiryDate']) : undefined}
            rules={[{ required: info['expiryDate'].isRequired, message: '此为必填项' }]}
            onChange={(e) => this.setState({ expiryDateT: e ? e : '' }, () => this.props.endDate(e))}
          />
        </div>
        {/* 结算日期 */}
        {/* {generateDatePicker({key:'settleDate'})} */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SingleDateC
            form={this.props.form} // form对象
            dataIndex={'bookMain.' + 'settleDate'}
            title=''
            placeholder=''
            disableBegin={
              expiryDateT
                ? moment(expiryDateT).subtract(1, 'day')
                : effectiveDateT
                ? moment(effectiveDateT).subtract(1, 'day')
                : tradeDateT
                ? moment(tradeDateT).subtract(1, 'day')
                : ''
            }
            disabled={info['settleDate'].isGrey || disabledImportant}
            initialValue={bookMain['settleDate'] ? moment(bookMain['settleDate']) : undefined}
            rules={[{ required: info['settleDate'].isRequired, message: '此为必填项' }]}
            onChange={(e) => this.setState({ settleDateT: e ? e : '' })}
          />
        </div>
        {/* 买卖方向 */}
        {generateSelect({ key: 'tradeDir' })}
        {/* 行权方向 */}
        {generateSelect({ key: 'excerciseDir', isRequired: Required1, disabled: Dis3 })}
        {/* 期初价格 */}
        {generateInputNumber({ key: 'initialPrice', onChange: this.initialPriceChange, precision: 2 })}
        {/* 名义本金 */}
        {generateInputNumber({ key: 'notional', disabled: Dis1, onChange: this.notionalChange, precision: 2 })}
        {/* 名义本金币种 */}
        {generateSelect({ key: 'notionalCcy' })}
        {/* 名义数量 */}
        {generateInputNumber({ key: 'quantity', precision: 2 })}
        {/* 行权价格率 */}
        {generateInputNumber({ key: 'strikeRate', precision: 2, onChange: this.strikeRateChange, disabled: Dis1 || Dis3, isRequired: Required1, unit: '%' })}
        {/* 行权价格 */}
        {generateInputNumber({ key: 'strike', precision: 2, onChange: this.strikeChange, disabled: Dis1 || Dis3, isRequired: Required1 })}
        {/* 期权费支付日期 */}
        {generateDatePicker({ key: 'premiumDate' })}
        {/* 期权费率 */}
        {generateInputNumber({ key: 'premiumRate', onChange: this.premiumRateChange, disabled: Dis2, precision: 2, unit: '%' })}
        {/* 期权费 */}
        {generateInputNumber({ key: 'premium', onChange: this.premiumChange, disabled: Dis2, precision: 2 })}
        {/* 期权费币种 */}
        {generateSelect({ key: 'premiumCcy' })}
        {/* 期末价格类型 */}
        <div style={{ width: '100%', height: '49px', overflow: 'hidden' }}>
          <SelectC
            style={{ width: '100%', height: '100%' }}
            dataIndex={'bookMain.priceType'}
            form={this.props.form}
            dataSource={priceTypeData[this.state.priceIndex]}
            placeholder=''
            disabled={info['priceType'].isGrey || disabledImportant}
            initialValue={bookMain['priceType']}
            rules={[{ required: info['priceType'].isRequired, message: '此为必填项' }]}
            positionBody={true}
          />
        </div>
        {/* 参与率 */}
        {generateInputNumber({ key: 'participationRate', precision: 2, unit: '%' })}
        {/* 票息 */}
        {generateInputNumber({ key: 'couponRate', precision: 2, unit: '%' })}
      </div>
    );
  }
}
